<template>
  <div class="app-container">
    <el-container>
      <!--          <el-header></el-header>-->
      <el-main>
        <el-divider content-position="left">链接信息</el-divider>
        <el-row class="line-item">
          <el-col :span="8">
            <el-autocomplete
                    class="inline-input"
                    v-model="device.ip"
                    :fetch-suggestions="ipQuerySearch"
                    placeholder="请输入IP"
                    size="mini">
              <template slot="prepend">IP</template>
            </el-autocomplete>
          </el-col>
          <el-col :span="8">
            <el-autocomplete
                    class="inline-input"
                    v-model="device.port"
                    :fetch-suggestions="portQuerySearch"
                    placeholder="请输入端口"
                    size="mini">
              <template slot="prepend">端口</template>
            </el-autocomplete>
          </el-col>
          <el-col :span="8">
            <el-button type="primary" size="mini" icon="el-icon-share" @click="linkConnect"  :loading="buttonLoading()" :disabled="connectStatus === 'connected'">链接</el-button>
            <el-button type="warning" size="mini" icon="el-icon-delete" @click="closeConnect" :loading="buttonLoading()" :disabled="buttonDisable()">断开</el-button>
            <el-button type="primary" size="mini" @click="testSend" :loading="buttonLoading()" :disabled="buttonDisable()">测试发送</el-button>
          </el-col>
        </el-row>

        <el-divider content-position="left">基本信息</el-divider>
        <el-row class="line-item">
          <el-col :span="6">
            <el-input
                    maxlength="20"
                    placeholder="SN"
                    v-model="device.sn"
                    size="mini"
            >

              <template slot="prepend">SN</template>
            </el-input>
          </el-col>
          <el-col :span="6" :offset="1">
            <el-tooltip effect="dark" :content="'电量：' + device.state.battery + '%'" placement="top-start">
              <el-slider v-model="device.state.battery" :min="0" :max="100" :show-tooltip="false"></el-slider>
            </el-tooltip>
            <!--                      <el-input-number v-model="device.state.battery" :min="0" :max="100" size="mini"></el-input-number>-->
            <!-- input-size="mini" show-input label="电量"-->
            <!--                      : {{device.state.battery}}%-->
          </el-col>
          <el-col :span="6" :offset="1">
            <el-checkbox label="充电" v-model="device.state.charge" size="mini"></el-checkbox>
            <el-checkbox label="静止" v-model="device.state.static" size="mini"></el-checkbox>
            <el-checkbox label="低功耗" v-model="device.state.lowPower" size="mini"></el-checkbox>
          </el-col>

          <el-col :span="4">
            <el-button type="primary" size="mini"  @click="sendHeart"  :loading="buttonLoading()" :disabled="buttonDisable()">心跳</el-button>
            <el-button type="primary" size="mini"  @click="sendGetConfig" :loading="buttonLoading()" :disabled="buttonDisable()">配置</el-button>
          </el-col>

        </el-row>

        <el-row class="line-item">
          <el-col :span="5">
            <el-input
                    size="mini"
                    placeholder="IMSI"
                    v-model="device.imsi"
                    clearable>
              <template slot="prepend">IMSI</template>
            </el-input>
          </el-col>
          <el-col :span="5" :offset="1">
            <el-input
                    size="mini"
                    placeholder="IMEI"
                    v-model="device.imei"
                    clearable>
              <template slot="prepend">IMEI</template>
            </el-input>
          </el-col>
          <el-col :span="5" :offset="1">

            <el-input
                    size="mini"
                    placeholder="设备秘钥"
                    v-model="device.deviceKey"
                    clearable>
              <template slot="prepend">秘钥</template>
            </el-input>
          </el-col>
          <el-col :span="6" :offset="1">
            <el-button type="primary" size="mini" @click="deviceRegister"  :loading="buttonLoading()" :disabled="buttonDisable()">设备注册</el-button>
            <el-button type="primary" size="mini" @click="deviceLogin" :loading="buttonLoading()" :disabled="buttonDisable()">设备登录</el-button>
          </el-col>
        </el-row>

        <el-row class="line-item">
          <el-col :span="6">
            <el-input
                    size="mini"
                    v-model="device.bindSn">
              <template slot="prepend">头/挂 SN</template>
            </el-input>
          </el-col>
          <el-col :span="4">
            <el-button type="primary" size="mini" @click="bindOtherCarrier"  :loading="buttonLoading()" :disabled="buttonDisable()">上挂</el-button>
            <el-button type="primary" size="mini" @click="unbindOtherCarrier"  :loading="buttonLoading()" :disabled="buttonDisable()">甩挂</el-button>
          </el-col>


          <el-col :span="3">
            <el-input
                    size="mini"
                    v-model="device.currentVersion">
              <template slot="prepend">版本</template>
            </el-input>
          </el-col>
          <el-col :span="3">
            <el-input
                    size="mini"
                    v-model="device.expectedVersion">
              <template slot="prepend">目标</template>
            </el-input>
          </el-col>
          <el-col :span="3">
            <el-input
                    type="number"
                    size="mini"
                    v-model="device.packNo">
              <template slot="prepend">包序</template>
            </el-input>
          </el-col>

          <el-col :span="4">
            <el-button type="primary" size="mini" @click="sendVersion"  :loading="buttonLoading()" :disabled="buttonDisable()">版本</el-button>
            <el-button type="primary" size="mini" @click="getOtaConfig"  :loading="buttonLoading()" :disabled="buttonDisable()">查询</el-button>
            <el-button type="primary" size="mini" @click="getOtaPackage"  :loading="buttonLoading()" :disabled="buttonDisable()">取包</el-button>
          </el-col>
        </el-row>


        <el-divider content-position="left">TPMS</el-divider>
        <el-row class="line-item">
          <el-col :span="16">
            <el-checkbox label="可疑" v-model="device.tpms.alarm.suspicious" size="mini" ></el-checkbox>
            <el-checkbox label="低电量" v-model="device.tpms.alarm.lowBattery" size="mini" ></el-checkbox>
            <el-checkbox label="无信号" v-model="device.tpms.alarm.signalError" size="mini" ></el-checkbox>
            <el-checkbox label="漏气" v-model="device.tpms.alarm.airLeak" size="mini" ></el-checkbox>
            <el-checkbox label="高温" v-model="device.tpms.alarm.highTemp" size="mini" ></el-checkbox>
            <el-checkbox label="低压" v-model="device.tpms.alarm.lowPressure" size="mini" ></el-checkbox>
            <el-checkbox label="高压" v-model="device.tpms.alarm.highPressure" size="mini" ></el-checkbox>
          </el-col>
          <el-col :span="8">
            <el-button type="primary" size="mini" @click="sendTpms"  :loading="buttonLoading()" :disabled="buttonDisable()">TPMS</el-button>
            <el-button type="primary" size="mini" @click="sendTpmsLoad"  :loading="buttonLoading()" :disabled="buttonDisable()">TPMS(载荷)</el-button>
            <el-button type="primary" size="mini" @click="sendTpmsEstimate"  :loading="buttonLoading()" :disabled="buttonDisable()">TPMS(预估)</el-button>
            <el-button type="primary" size="mini" @click="syncColdPressure"  :loading="buttonLoading()" :disabled="buttonDisable()">同步冷胎</el-button>
          </el-col>
        </el-row>


        <el-row class="line-item">
          <el-col :span="3">
            <el-input
                    size="mini"
                    v-model="device.tpms.sensorNo">
              <template slot="prepend">传感器号</template>
            </el-input>
          </el-col>
          <el-col :span="3" :offset="1">
            <el-input
                    type="number"
                    size="mini"
                    v-model="device.tpms.wheelId">
              <template slot="prepend">轮位ID</template>
            </el-input>
          </el-col>
          <el-col :span="3" :offset="1">
            <el-input
                    size="mini"
                    v-model="device.tpms.position">
              <template slot="prepend">轮位</template>
            </el-input>
          </el-col>
          <el-col :span="3" :offset="1">
            <el-input
                    type="number"
                    size="mini"
                    v-model="device.tpms.temp">
              <template slot="prepend">胎温</template>
            </el-input>
          </el-col>
          <el-col :span="3" :offset="1">
            <el-input
                    type="number"
                    size="mini"
                    v-model="device.tpms.pressure">
              <template slot="prepend">胎压</template>
            </el-input>
          </el-col>
          <el-col :span="3" :offset="1">
            <el-date-picker
                    size="mini"
                    value-format = "ddMMyyHHmmss"
                    v-model="device.tpms.timeStamp"
                    type="datetime"
                    placeholder="选择TPMS时间"
                    align="right"
                    :picker-options="pickerOptions">
            </el-date-picker>
          </el-col>
        </el-row>

        <el-row class="line-item">
          <el-col :span="3">
            <el-input
                    type="number"
                    size="mini"
                    v-model="device.tpms.loading">
              <template slot="prepend">载荷</template>
            </el-input>
          </el-col>

          <el-col :span="3" :offset="1">
            <el-input
                    type="number"
                    size="mini"
                    v-model="device.tpms.restDepth">
              <template slot="prepend">余深</template>
            </el-input>
          </el-col>
          <el-col :span="3" :offset="1">
            <el-input
                    type="number"
                    size="mini"
                    v-model="device.tpms.battery">
              <template slot="prepend">电量</template>
            </el-input>
          </el-col>
          <el-col :span="3" :offset="1">
            <el-input
                    type="number"
                    size="mini"
                    v-model="device.tpms.acc">
              <template slot="prepend">加速度</template>
            </el-input>
          </el-col>
          <el-col :span="3" :offset="1">
            <el-input
                    type="number"
                    size="mini"
                    v-model="device.tpms.estimateTemp">
              <template slot="prepend">预估胎温</template>
            </el-input>
          </el-col>
          <el-col :span="3" :offset="1">
            <el-input
                    type="number"
                    size="mini"
                    v-model="device.tpms.sensorTemp">
              <template slot="prepend">传感器胎温</template>
            </el-input>
          </el-col>
        </el-row>


        <el-row class="line-item">
          <el-col :span="3">
            <el-input
                    type="number"
                    size="mini"
                    v-model="device.tpms.coldPressure.cold">
              <template slot="prepend">coldPressure</template>
            </el-input>
          </el-col>
          <el-col :span="3" :offset="1">
            <el-input
                    type="number"
                    size="mini"
                    v-model="device.tpms.coldPressure.coldPressure0">
              <template slot="prepend">coldPressure0</template>
            </el-input>
          </el-col>
          <el-col :span="3" :offset="1">
            <el-date-picker
                    size="mini"
                    value-format = "timestamp"
                    v-model="device.tpms.coldPressure.timeStamp0"
                    type="datetime"
                    placeholder="timeStamp0"
                    align="right"
                    :picker-options="pickerOptions">
            </el-date-picker>
          </el-col>
          <el-col :span="3" :offset="1">
            <el-input
                    type="number"
                    size="mini"
                    v-model="device.tpms.coldPressure.pressureT">
              <template slot="prepend">pressureT</template>
            </el-input>
          </el-col>
          <el-col :span="3" :offset="1">
            <el-input
                    type="number"
                    size="mini"
                    v-model="device.tpms.coldPressure.tempT">
              <template slot="prepend">tempT</template>
            </el-input>
          </el-col>
          <el-col :span="3" :offset="1">
            <el-date-picker
                    value-format = "timestamp"
                    size="mini"
                    v-model="device.tpms.coldPressure.timeStampT"
                    type="datetime"
                    placeholder="timeStampT"
                    align="right"
                    :picker-options="pickerOptions">
            </el-date-picker>
          </el-col>
        </el-row>




        <el-divider content-position="left">GPS</el-divider>
        <el-row class="line-item">
          <el-col :span="2">
            <el-select size="mini" v-model="device.gps.lngD" placeholder="东经/西经">
              <el-option label="东经" value="E"></el-option>
              <el-option label="西经" value="W"></el-option>
            </el-select>
          </el-col>
          <el-col :span="3">
            <el-input
                    size="mini"
                    v-model="device.gps.lng">
            </el-input>
          </el-col>

          <el-col :span="2" :offset="1">
            <el-select size="mini" v-model="device.gps.latD" placeholder="南纬/北纬">
              <el-option label="南纬" value="S"></el-option>
              <el-option label="北纬" value="N"></el-option>
            </el-select>
          </el-col>
          <el-col :span="3">
            <el-input
                    size="mini"
                    v-model="device.gps.lat">
            </el-input>
          </el-col>
          <el-col :span="3" :offset="1">
            <el-input
                    type="number"
                    size="mini"
                    v-model="device.gps.altitude">
              <template slot="prepend">海拔</template>
            </el-input>
          </el-col>
          <el-col :span="3" :offset="1">
            <el-input
                    type="number"
                    size="mini"
                    v-model="device.gps.direct">
              <template slot="prepend">航向</template>
            </el-input>
          </el-col>
          <el-col :span="3" :offset="1">
            <el-input
                    type="number"
                    size="mini"
                    v-model="device.gps.speed">
              <template slot="prepend">速度</template>
            </el-input>
          </el-col>

        </el-row>
        <el-row class="line-item">
          <el-col :span="6">
            <el-input
                    size="mini"
                    v-model="device.gps.auto.start.total">
              <template slot="prepend">开始</template>
            </el-input>
          </el-col>

          <el-col :span="6">
            <el-input
                    size="mini"
                    v-model="device.gps.auto.stop.total">
              <template slot="prepend">结束</template>
            </el-input>
          </el-col>

          <el-col :span="3" :offset="1">
            <el-date-picker
                    value-format = "ddMMyyHHmmss"
                    size="mini"
                    v-model="device.gps.timeStamp"
                    type="datetime"
                    placeholder="选择GPS时间"
                    align="right"
                    :picker-options="pickerOptions">
            </el-date-picker>
          </el-col>


          <el-col :span="6"  :offset="2">
            <el-button type="primary" size="mini" @click="sendGps"  :loading="buttonLoading()" :disabled="buttonDisable()">GPS</el-button>
<!--            <el-popover-->
<!--                    placement="right"-->
<!--                    width="600"-->
<!--                    trigger="click">-->
<!--              <MapGpsSelect v-model="latLngList" :count="mapPointCount" @drivingComplete="driveComplete"></MapGpsSelect>-->
<!--              <el-button slot="reference" type="primary" size="mini"  :loading="buttonLoading()" :disabled="buttonDisable()">地图取点</el-button>-->
<!--            </el-popover>-->
            <el-button type="primary" size="mini"  :loading="buttonLoading()" :disabled="buttonDisable()" @click="mapVisible = true" v-if="!timer.gpsTimerRunning">地图取点</el-button>
            <el-button type="primary" size="mini" @click="autoSendGps"  :loading="buttonLoading()" :disabled="buttonDisable()" v-if="!timer.gpsTimerRunning">自动发送</el-button>
            <el-button type="primary" size="mini" @click="stopAutoSendGps"  :loading="buttonLoading()" :disabled="buttonDisable()" v-if="timer.gpsTimerRunning">停止</el-button>
            <div v-if="timer.gpsTimerRunning" style="width: 150px">
              <el-progress :text-inside="true" :stroke-width="16" :percentage="parseFloat( (autoGpsCurrentIndex/device.gps.auto.path.length *100).toFixed(0) )"  status="success"></el-progress>
            </div>

            <el-dialog
                    title="坐标拾取"
                    :visible.sync="mapVisible"
                    width="50%">
              <MapGpsSelect v-model="latLngList" :count="mapPointCount" @drivingComplete="driveComplete"></MapGpsSelect>
            </el-dialog>



          </el-col>

        </el-row>

<!--        <el-row v-if="timer.gpsTimerRunning" style="width: 200px">-->
<!--          <el-progress :text-inside="true" :stroke-width="16" :percentage=" (autoGpsCurrentIndex/device.gps.auto.path.length *100).toFixed(0) "  status="success"></el-progress>-->
<!--        </el-row>-->

        <el-divider content-position="left">自定义</el-divider>
        <el-row class="line-item">
          <el-col :span="6">
            <el-input
                    type="number"
                    size="mini"
                    v-model="device.custom.cmd">
              <template slot="prepend">CMD</template>
            </el-input>
          </el-col>

          <el-col :span="11" :offset="1">
            <el-input
                    size="mini"
                    v-model="device.custom.body">
              <template slot="prepend">内容</template>
            </el-input>
          </el-col>
          <el-col :span="5"  :offset="1">
            <el-button type="primary" size="mini" @click="sendCustom"  :loading="buttonLoading()" :disabled="buttonDisable()">发送</el-button>
          </el-col>
        </el-row>


        <!--              <el-divider content-position="left">充放气(待定)</el-divider>-->
        <el-divider content-position="left">外设相关</el-divider>
        <el-row class="line-item">
          <el-col :span="3">
            <el-input
                    type="number"
                    size="mini"
                    v-model="device.peripheral.id">
              <template slot="prepend">外设ID</template>
            </el-input>
          </el-col>

          <el-col :span="4" :offset="1">
            <el-select size="mini" v-model="device.peripheral.type" placeholder="外设类型">
              <el-option label="自动定位线束" value="10"></el-option>
            </el-select>
          </el-col>

          <el-col :span="3" :offset="1">
            <el-input
                    size="mini"
                    v-model="device.peripheral.currentVersion">
              <template slot="prepend">版本</template>
            </el-input>
          </el-col>

          <el-col :span="3"  :offset="1">
            <el-button type="primary" size="mini" @click="syncPeripheral"  :loading="buttonLoading()" :disabled="buttonDisable()">同步</el-button>
          </el-col>
        </el-row>

        <el-row class="line-item">
          <el-col :span="3">
            <el-input
                    size="mini"
                    v-model="device.peripheral.expectedVersion">
              <template slot="prepend">目标</template>
            </el-input>
          </el-col>

          <el-col :span="3" :offset="1">
            <el-input
                    type="number"
                    size="mini"
                    v-model="device.peripheral.packNo">
              <template slot="prepend">包序</template>
            </el-input>
          </el-col>


          <el-col :span="8"  :offset="1">
            <el-button type="primary" size="mini" @click="sendPeripheralVersion"  :loading="buttonLoading()" :disabled="buttonDisable()">版本</el-button>
            <el-button type="primary" size="mini" @click="getPeripheralConfig"  :loading="buttonLoading()" :disabled="buttonDisable()">配置</el-button>
            <el-button type="primary" size="mini" @click="getPeripheralPackage"  :loading="buttonLoading()" :disabled="buttonDisable()">取包</el-button>
          </el-col>
        </el-row>


      </el-main>


      <el-footer>
        <el-divider content-position="left">日志打印</el-divider>
        <el-input
                type="textarea"
                :rows="10"
                v-model="logInfo"
                clearable>
        </el-input>
      </el-footer>
    </el-container>
  </div>
</template>

<script>
    import { ipcRenderer  } from "electron";

    import {utils} from "../../utils/utils";
    import MapGpsSelect from "../../components/map/MapGpsSelect";

    export default {
        data:()=> {
            return {

                ipSuggest : [
                    { "value": '192.168.10.37'},
                    { "value": '10.1.80.247'},
                    { "value":'10.253.0.187'},
                    { "value":'tcp-t.zhilunkeji.com'},
                    { "value":'tcp.zhilun.com'},
                ],
                portSuggest : [
                    { "value": '9113'},
                    { "value": '19113'},
                    { "value": '30633'},
                ],

                connectStatus : 'close' ,
                tcpClient : null,

                logInfo : "",

                device : {

                    ip: '192.168.10.37',
                    port: '9113',

                    sn  :  "01060000000B",
                    deviceKey : null ,
                    currentVersion : null,
                    expectedVersion : null ,
                    packNo : null,

                    bindSn : null ,

                    state : {
                        charge: true,
                        lowPower : false ,
                        static : false,
                        battery : 55,
                    },

                    tpms :{
                        alarm : {
                            suspicious : false,
                            lowBattery : false,
                            signalError: false,
                            airLeak: false,
                            highTemp: false,
                            lowPressure: false,
                            highPressure: false,
                        },
                        sensorNo : null,
                        wheelId : null,
                        position : null ,
                        temp : null ,
                        estimateTemp : null,
                        sensorTemp : null ,
                        pressure : null ,
                        timeStamp : null,

                        loading: null ,
                        restDepth : null ,

                        battery : null ,
                        acc : null,

                        coldPressure:{
                            cold : null ,
                            coldPressure0: null ,
                            timeStamp0: null,
                            pressureT : null ,
                            tempT : null ,
                            timeStampT : null,
                        }

                    },

                    gps :{
                        lat : null ,
                        lng : null ,
                        latD : 'N' ,
                        lngD : 'E' ,
                        altitude : null ,
                        direct : null ,
                        speed : null ,
                        timeStamp : null,

                        auto : {
                            path : [],
                            start :{
                                total : null,
                                lat : null ,
                                lng : null ,
                            },
                            stop :{
                                total : null,
                                lat : null ,
                                lng : null ,
                            },
                        }
                    },

                    //自定义
                    custom :{
                        cmd : null ,
                        body : null ,
                    },

                    inflate :{
                        status : null,
                        mode : null,
                        position : null ,
                        exception : null,
                    },

                    //外设
                    peripheral:{
                        id : null ,
                        type : null ,
                        currentVersion : null,
                        expectedVersion : null,
                        packNo : null,

                    },
                    imsi : null,
                    imei : null ,

                },

                pickerOptions: {
                    shortcuts: [{
                        text: '今天',
                        onClick(picker) {
                            picker.$emit('pick', new Date());
                        }
                    }, {
                        text: '昨天',
                        onClick(picker) {
                            const date = new Date();
                            date.setTime(date.getTime() - 3600 * 1000 * 24);
                            picker.$emit('pick', date);
                        }
                    }, {
                        text: '一周前',
                        onClick(picker) {
                            const date = new Date();
                            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
                            picker.$emit('pick', date);
                        }
                    }]
                },

                mapPointCount : 2,
                mapVisible : false,
                autoGpsCurrentIndex : 0,
                latLngList : [] ,
                gpsCount : 10,
                lngArr : [],
                latArr : [],
                tsArr : [],

                timer : {
                    gpsTimer : null,
                    gpsTimerRunning : false,
                }
            }
        },

        components: {
            MapGpsSelect,
        },

        watch: {
            device: {
                handler : function(newVal, oldVal){
                    this.saveDevice(newVal);
                },
                deep: true,
                // immediate: true
            },
            latLngList : {
                handler : function(newVal, oldVal){
                    if(newVal.length >= 1){
                        this.device.gps.auto.start.lat = newVal[0].lat;
                        this.device.gps.auto.start.lng = newVal[0].lng;
                        this.device.gps.auto.start.total = "" + this.device.gps.auto.start.lng + "," + this.device.gps.auto.start.lat;
                    }
                    if(newVal.length >= 2){
                        this.device.gps.auto.stop.lat = newVal[1].lat;
                        this.device.gps.auto.stop.lng = newVal[1].lng;
                        this.device.gps.auto.stop.total = "" + this.device.gps.auto.stop.lng   + "," + this.device.gps.auto.stop.lat;
                    }
                },
                deep: true,
            }
        },


        mounted() {
            this.resourceDevice();
            // console.log(crc16(str2Bytes("245F0000000101060000000B37000024")));
            // console.log( parseInt(("" + 1+1).padStart(8 , "0"),2));
            // var a = 55;
            // console.log(a.toString(16))
            // console.log(generateTcpData("01060000000B" , this.device.state , 65531 , "00"));
            // console.log(CMD)
        },


        methods: {
            buttonLoading(){
                return this.connectStatus === 'connecting';
            },

            buttonDisable(){
                return this.connectStatus === 'close';
            },

            ipQuerySearch(queryString, cb) {
                // var ip = this.ip;
                // var results = queryString ? this.ipSuggest.filter(this.createFilter(queryString)) : this.ipSuggest;
                var results = this.ipSuggest;
                cb(results);
            },
            portQuerySearch(queryString, cb) {
                // var port = this.port;
                // var results = queryString ? this.portSuggest.filter(this.createFilter(queryString)) : this.portSuggest;
                var results =  this.portSuggest;
                cb(results);
            },

            createFilter(queryString) {
                return (item) => {
                    return (item.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
                };
            },

            sendHeart() {
                const body = "";
                const sendData = utils.generateTcpData(this.device.sn , this.device.state  , utils.CMD.HEART_V3 , body);
                this.dataSend(sendData);
            },
            sendGetConfig() {
                const body = "";
                const sendData = utils.generateTcpData(this.device.sn , this.device.state  , utils.CMD.GET_DEVICE_CONFIG , body);
                this.dataSend(sendData);
            },
            deviceRegister() {
                const body =
                    utils.str2HexAscii(this.device.imsi) + utils.TCP_VALUE_SPLIT +
                    utils.str2HexAscii(this.device.imei);
                const sendData = utils.generateTcpData(this.device.sn , this.device.state  , utils.CMD.REG_V3 , body);
                this.dataSend(sendData);
            },
            deviceLogin() {
                const body = utils.str2HexAscii(this.device.deviceKey);
                const sendData = utils.generateTcpData(this.device.sn , this.device.state  , utils.CMD.DEVICE_LOGIN_V3 , body);
                this.dataSend(sendData);
            },
            bindOtherCarrier(){
                const body = utils.str2HexAscii(this.device.bindSn);
                const sendData = utils.generateTcpData(this.device.sn , this.device.state  , utils.CMD.AUTO_BIND_V3 , body);
                this.dataSend(sendData);
            },
            unbindOtherCarrier(){
                const body = "";
                const sendData = utils.generateTcpData(this.device.sn , this.device.state  , utils.CMD.AUTO_UNBIND_V3 , body);
                this.dataSend(sendData);
            },
            sendVersion(){
                const body = this.device.currentVersion;
                const sendData = utils.generateTcpData(this.device.sn , this.device.state  , utils.CMD.VERSION , body);
                this.dataSend(sendData);
            },
            getOtaConfig(){
                const body = this.device.expectedVersion;
                const sendData = utils.generateTcpData(this.device.sn , this.device.state  , utils.CMD.GET_OTA_CONFIG , body);
                this.dataSend(sendData);
            },
            getOtaPackage(){
                const body = this.device.expectedVersion + utils.TCP_VALUE_SPLIT +
                    utils.str2HexAscii(this.device.packNo);;
                const sendData = utils.generateTcpData(this.device.sn , this.device.state  , utils.CMD.GET_OTA_PACKAGE , body);
                this.dataSend(sendData);
            },

            generateTpmsContent(type = utils.CMD.TPMS_V3) {
                const sensorType = "1";

                const suspicious = this.device.tpms.alarm['suspicious'] ? 1 : 0;
                console.log("suspicious : " + suspicious);
                const lowBattery = this.device.tpms.alarm['lowBattery'] ? 1 : 0;
                console.log("lowBattery : " + lowBattery);
                const signalError = this.device.tpms.alarm['signalError'] ? 1 : 0;
                console.log("signalError : " + signalError);
                const airLeak = this.device.tpms.alarm['airLeak'] ? 1 : 0;
                console.log("airLeak : " + airLeak);
                const highTemp = this.device.tpms.alarm['highTemp'] ? 1 : 0;
                console.log("highTemp : " + highTemp);
                const lowPressure = this.device.tpms.alarm['lowPressure'] ? 1 : 0;
                console.log("lowPressure : " + lowPressure);
                const highPressure = this.device.tpms.alarm['highPressure'] ? 1 : 0;
                console.log("highPressure : " + highPressure);
                const alramFlagStr = (""    + highPressure + lowPressure + highTemp + airLeak + signalError  + lowBattery + suspicious ).padStart(16 , "0");
                console.log("alramFlagStr : " + alramFlagStr);
                const alramFlag = "" + parseInt(alramFlagStr,2);
                console.log("alramFlag : " + alramFlag);

                var body = "";

                switch(type){
                    case utils.CMD.TPMS_V3:
                        body = utils.str2HexAscii(sensorType) + utils.TCP_VALUE_SPLIT +
                            utils.str2HexAscii(this.device.tpms.sensorNo) + utils.TCP_VALUE_SPLIT +
                            utils.str2HexAscii(this.device.tpms.wheelId) + utils.TCP_VALUE_SPLIT +
                            utils.str2HexAscii(this.device.tpms.position) + utils.TCP_VALUE_SPLIT +
                            utils.str2HexAscii(this.device.tpms.temp) + utils.TCP_VALUE_SPLIT +
                            utils.str2HexAscii(this.device.tpms.pressure) + utils.TCP_VALUE_SPLIT +
                            utils.str2HexAscii(alramFlag) + utils.TCP_VALUE_SPLIT +
                            utils.str2HexAscii(this.device.tpms.timeStamp) ;
                        break;
                    case utils.CMD.TPMS_LOAD:
                        body = utils.str2HexAscii(sensorType) + utils.TCP_VALUE_SPLIT +
                            utils.str2HexAscii(this.device.tpms.sensorNo) + utils.TCP_VALUE_SPLIT +
                            utils.str2HexAscii(this.device.tpms.wheelId) + utils.TCP_VALUE_SPLIT +
                            utils.str2HexAscii(this.device.tpms.position) + utils.TCP_VALUE_SPLIT +
                            utils.str2HexAscii(this.device.tpms.temp) + utils.TCP_VALUE_SPLIT +
                            utils.str2HexAscii(this.device.tpms.pressure) + utils.TCP_VALUE_SPLIT +

                            utils.str2HexAscii(this.device.tpms.loading) + utils.TCP_VALUE_SPLIT +
                            utils.str2HexAscii(this.device.tpms.restDepth) + utils.TCP_VALUE_SPLIT +
                            utils.str2HexAscii(this.device.tpms.battery) + utils.TCP_VALUE_SPLIT +
                            utils.str2HexAscii(this.device.tpms.acc) + utils.TCP_VALUE_SPLIT +

                            utils.str2HexAscii(alramFlag) + utils.TCP_VALUE_SPLIT +
                            utils.str2HexAscii(this.device.tpms.timeStamp) ;
                        break;
                    case utils.CMD.TPMS_ACC:
                        break;
                    case utils.CMD.TPMS_ESTIMATE:
                        body = utils.str2HexAscii(sensorType) + utils.TCP_VALUE_SPLIT +
                            utils.str2HexAscii(this.device.tpms.sensorNo) + utils.TCP_VALUE_SPLIT +
                            utils.str2HexAscii(this.device.tpms.wheelId) + utils.TCP_VALUE_SPLIT +
                            utils.str2HexAscii(this.device.tpms.position) + utils.TCP_VALUE_SPLIT +
                            utils.str2HexAscii(this.device.tpms.temp) + utils.TCP_VALUE_SPLIT +
                            utils.str2HexAscii(this.device.tpms.pressure) + utils.TCP_VALUE_SPLIT +

                            utils.str2HexAscii(this.device.tpms.acc) + utils.TCP_VALUE_SPLIT +

                            utils.str2HexAscii(alramFlag) + utils.TCP_VALUE_SPLIT +
                            utils.str2HexAscii(this.device.tpms.timeStamp) + utils.TCP_VALUE_SPLIT +
                            utils.str2HexAscii(this.device.tpms.estimateTemp) + utils.TCP_VALUE_SPLIT +
                            utils.str2HexAscii(this.device.tpms.sensorTemp) ;
                        break;
                }

                return body;

            },

            sendTpms(){
                const body = this.generateTpmsContent();
                const sendData = utils.generateTcpData(this.device.sn , this.device.state  , utils.CMD.TPMS_V3 , body);
                this.dataSend(sendData);
            },
            sendTpmsLoad(){
                const body = this.generateTpmsContent(utils.CMD.TPMS_LOAD );
                const sendData = utils.generateTcpData(this.device.sn , this.device.state  , utils.CMD.TPMS_LOAD , body);
                this.dataSend(sendData);
            },
            sendTpmsEstimate(){
                const body = this.generateTpmsContent(utils.CMD.TPMS_ESTIMATE );
                const sendData = utils.generateTcpData(this.device.sn , this.device.state  , utils.CMD.TPMS_ESTIMATE , body);
                this.dataSend(sendData);
            },
            syncColdPressure(){
                console.log(utils.strToTs(this.device.tpms.timeStamp , "DDMMYYHHmmss"));
                const body =
                    utils.str2HexAscii(this.device.tpms.position) + utils.TCP_VALUE_SPLIT +
                    utils.str2HexAscii(this.device.tpms.sensorNo) + utils.TCP_VALUE_SPLIT +
                    utils.str2HexAscii(this.device.tpms.coldPressure.cold) + utils.TCP_VALUE_SPLIT +
                    utils.str2HexAscii(utils.strToTs(this.device.tpms.timeStamp , "DDMMYYHHmmss")) + utils.TCP_VALUE_SPLIT +
                    utils.str2HexAscii(this.device.tpms.coldPressure.coldPressure0) + utils.TCP_VALUE_SPLIT +
                    utils.str2HexAscii(this.device.tpms.coldPressure.timeStamp0 / 1000) + utils.TCP_VALUE_SPLIT +
                    utils.str2HexAscii(this.device.tpms.coldPressure.pressureT) + utils.TCP_VALUE_SPLIT +
                    utils.str2HexAscii(this.device.tpms.coldPressure.tempT ) + utils.TCP_VALUE_SPLIT +
                    utils.str2HexAscii(this.device.tpms.coldPressure.timeStampT / 1000)
                ;
                const sendData = utils.generateTcpData(this.device.sn , this.device.state  , utils.CMD.SYNC_COLD_PRESSURE , body);
                this.dataSend(sendData);
            },

            generateGpsContent(type = utils.CMD.GPS_BRIEF,lng = null , lat = null , ts = null, i = 0 ,random=false){
                const body =
                    utils.str2HexAscii(utils.gpsToDegMin(lat ? lat : this.device.gps.lat,i)) + utils.TCP_VALUE_SPLIT +
                    utils.str2HexAscii(this.device.gps.latD) + utils.TCP_VALUE_SPLIT +
                    utils.str2HexAscii(utils.gpsToDegMin(lng ? lng : this.device.gps.lng,i)) + utils.TCP_VALUE_SPLIT +
                    utils.str2HexAscii(this.device.gps.lngD) + utils.TCP_VALUE_SPLIT +
                    utils.str2HexAscii(random ? Math.floor(Math.random()*(360-0)+0) :this.device.gps.direct) + utils.TCP_VALUE_SPLIT +
                    utils.str2HexAscii(ts ? ts : this.device.gps.timeStamp) + utils.TCP_VALUE_SPLIT +
                    utils.str2HexAscii(random ? Math.floor(Math.random()*(120-0)+0) : this.device.gps.speed) + utils.TCP_VALUE_SPLIT +
                    utils.str2HexAscii(random ? Math.floor(Math.random()*(2000-0)+0) :this.device.gps.altitude)
                ;

                return body;
            },

            generateGpsContentBatch(type = utils.CMD.GPS_BRIEF,lngArr = [] , latArr = [] , tsArr = [], i = 0 ){
              var body = '';
              for(var index =0 ; index<lngArr.length ; index++){
                  body += this.generateGpsContent(type , lngArr[index] , latArr[index] , tsArr[index], 0 , true);
                  if(index < lngArr.length-1){
                    body += utils.TCP_LIST_ITEM_SPLIT;
                  }
              }

              return body;
            },



          sendGps(){
                const body = this.generateGpsContent(utils.CMD.GPS_BRIEF );
                const sendData = utils.generateTcpData(this.device.sn , this.device.state  , utils.CMD.GPS_BRIEF , body);
                this.dataSend(sendData);
            },

            driveComplete(data){
                this.autoGpsCurrentIndex = 0;
                this.device.gps.auto.path = [];
                var that = this;
                data.routes[0].steps.forEach(( step , index) => {
                    step.path.forEach(( lnglat , index2) => {
                        that.device.gps.auto.path.push(lnglat)
                    })
                })
                this.$message("路径规划完成,共计" + this.device.gps.auto.path.length + "个点,点击自动发送开始自动运行");
                this.mapVisible = false;

            },

            autoSendGps(){
                if(utils.isEmpty(this.device.gps.auto.start.total) || utils.isEmpty(this.device.gps.auto.stop.total) || this.device.gps.auto.path.length === 0){
                    this.$message({
                        message: '请选择起始结束位置',
                        type: 'warning'
                    });
                    return;
                }
                this.$message({
                    message: '开始自动发送',
                    type: 'success'
                });

                this.gpsTimeInit();
                this.timer.gpsTimerRunning = true;
                this.timer.gpsTimer = setInterval( this.autoSendGpsSingle ,1000)
            },
            gpsTimeInit(){
                clearInterval(this.timer.gpsTimer);
                this.timer.gpsTimerRunning = false;
                this.autoGpsCurrentIndex = 0;
            },

            autoSendGpsSingle(){
                if(this.autoGpsCurrentIndex >= this.device.gps.auto.path.length){
                    this.gpsTimeInit();
                    return;
                }
                // console.log(this.autoGpsCurrentIndex);
                // console.log(this.device.gps.auto.path.length);

                if((this.autoGpsCurrentIndex+1)%this.gpsCount !== 0){
                  const time =  utils.getCurrentTime("DDMMYYHHmmss",0);
                  this.tsArr.push(time);
                  // console.log(this.tsArr);
                  const currentLngLat = this.device.gps.auto.path[this.autoGpsCurrentIndex];
                  const currentLngLatWGS = utils.gcj02towgs84(currentLngLat[0] , currentLngLat[1]);
                  const currentLng = currentLngLatWGS[0];
                  const currentLat = currentLngLatWGS[1]
                  this.lngArr.push(currentLng);
                  this.latArr.push(currentLat);
                }

              if((this.autoGpsCurrentIndex+1)%this.gpsCount === 0 || this.autoGpsCurrentIndex === this.device.gps.auto.path.length-1){
                  const body = this.generateGpsContentBatch(utils.CMD.GPS_BRIEF ,this.lngArr , this.latArr , this.tsArr);
                  const sendData = utils.generateTcpData(this.device.sn , this.device.state  , utils.CMD.GPS_BRIEF , body);
                  this.dataSend(sendData);
                  this.tsArr = [];
                  this.lngArr = [];
                  this.latArr = [];

                }
                this.autoGpsCurrentIndex++;
            },

            stopAutoSendGps(){
                clearInterval(this.timer.gpsTimer);
                this.timer.gpsTimerRunning = false;
            },
            sendCustom(){
                const body = this.device.custom.body;
                const sendData = utils.generateTcpData(this.device.sn , this.device.state  , this.device.custom.cmd , body);
                this.dataSend(sendData);
            },
            getPeripheralPackage(){
                const body = utils.str2HexAscii(this.device.peripheral.id) + utils.TCP_VALUE_SPLIT +
                    utils.str2HexAscii(this.device.peripheral.type)  + utils.TCP_VALUE_SPLIT +
                    utils.str2HexAscii(this.device.peripheral.expectedVersion)+ utils.TCP_VALUE_SPLIT +
                    utils.str2HexAscii(this.device.peripheral.packNo)
                ;
                const sendData = utils.generateTcpData(this.device.sn , this.device.state  , utils.CMD.GET_OTA_CONFIG_PERIPHERAL , body);
                this.dataSend(sendData);
            },
            getPeripheralConfig(){
                const body = utils.str2HexAscii(this.device.peripheral.id) + utils.TCP_VALUE_SPLIT +
                    utils.str2HexAscii(this.device.peripheral.type)  + utils.TCP_VALUE_SPLIT +
                    utils.str2HexAscii(this.device.peripheral.expectedVersion)
                ;
                const sendData = utils.generateTcpData(this.device.sn , this.device.state  , utils.CMD.GET_OTA_CONFIG_PERIPHERAL , body);
                this.dataSend(sendData);
            },
            syncPeripheral(){
                const body = utils.str2HexAscii(this.device.peripheral.type) + utils.TCP_VALUE_SPLIT +
                    utils.str2HexAscii(this.device.peripheral.currentVersion)
                ;
                const sendData = utils.generateTcpData(this.device.sn , this.device.state  , utils.CMD.SYNC_PERIPHERAL , body);
                this.dataSend(sendData);
            },
            sendPeripheralVersion(){
                const body = utils.str2HexAscii(this.device.peripheral.id) + utils.TCP_VALUE_SPLIT +
                    utils.str2HexAscii(this.device.peripheral.type)  + utils.TCP_VALUE_SPLIT +
                    utils.str2HexAscii(this.device.peripheral.currentVersion)
                ;
                const sendData = utils.generateTcpData(this.device.sn , this.device.state  , utils.CMD.VERSION_PERIPHERAL , body);
                this.dataSend(sendData);
            },
            testSend(){
                const body = "31";
                const sendData = utils.generateTcpData(this.device.sn , this.device.state  , utils.CMD.TEST_V3 , body);
                this.dataSend(sendData);
            },



            linkConnect() {
                this.dataReceiveListen();
                this.dataErrorListen();
                this.tcpEndListen();
                this.connectStatus = 'connecting';
                ipcRenderer.invoke("tcpConnect",{
                    ip : this.device.ip,
                    port : this.device.port
                }).then((res) => {
                    this.logAppend("TCP" , "connected");
                    this.connectStatus = 'connected';

                    this.$message({
                        message: '链接成功，恭喜发财',
                        type: 'success'
                    });

                }).catch(e => {
                    this.connectStatus = 'close';
                });
            },

            dataSend(data) {
                this.logAppend("发送",data);
                ipcRenderer.invoke("tcpSendData",utils.str2Bytes(data));
                // this.saveDevice()
                this.$message({
                    message: '发送成功',
                    duration : 1000,
                    type: 'success'
                });
            },

            saveDevice(newConfig){
                utils.setCacheObject(utils.CACHE_KEY.TCP_CONFIG , newConfig)
            },

            resourceDevice() {
                const config = utils.getCacheObject(utils.CACHE_KEY.TCP_CONFIG)
                if (config) {
                    this.device = utils.deepClone(config);
                }
            },

            dataReceiveListen() {
                ipcRenderer.removeAllListeners("tcpReceiveData");
                ipcRenderer.on("tcpReceiveData" , (e, data) => {
                    this.logAppend("接收",utils.bytes2Str(data));
                })
            },
            dataErrorListen() {
                ipcRenderer.removeAllListeners("tcpError");
                ipcRenderer.on("tcpError" , (e, err) => {
                    this.closeConnect();
                    this.logAppend("TCP","connect close");
                    this.$message({
                        message: '链接错误，傻傻摸不到头脑',
                        type: 'warning'
                    });

                })
            },

            tcpEndListen() {
                ipcRenderer.removeAllListeners("tcpEnd");
                ipcRenderer.on("tcpEnd" , (e, err) => {
                    this.closeConnect();
                    this.logAppend("TCP","connect close");
                    this.$message({
                        message: '链接断开，被服务器一脚踹开',
                        type: 'warning'
                    });

                })
            },


            closeConnect() {
                ipcRenderer.invoke("tcpClose").then((res) => {
                    this.connectStatus = 'close';


                    this.gpsTimeInit()

                })
            },
            logAppend(title , data){
                this.logInfo = "[" + title + '][' + utils.getCurrentTime() + "]\r\n" + data + "\r\n" + this.logInfo;
            }
        }
    }

</script>
<style lang="scss">

  .app-container ::-webkit-scrollbar {
    display: block !important;
    background-color: #fff;
    width: 100%;
    height: 100%;
  }
  .el-table__body-wrapper::-webkit-scrollbar-thumb {
    border-radius:5px;
    -webkit-box-shadow: inset 0 0 6px rgba(70, 57, 57, 0.3);
    background-color: rgba(0, 0, 0, .1)

  }

  .line-item{
    padding: 10px 0;
    white-space:nowrap;

    .el-col{
      line-height: 28px;

      .el-row{
        overflow:hidden;
      }
    }
  }




</style>
